﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Microsoft.VisualBasic;
using xpds_ProductMonitor.Models;
using System.ComponentModel;
using System.Windows.Controls;
using xpds_ProductMonitor.UserControls;
using System.Windows.Threading;
using System.IO.Ports;
using System.Windows;
using System.Windows.Documents;
using CommunityToolkit.Mvvm.ComponentModel;
using xpds_ProductMonitor.BLL;
using xpds_ProductMonitor.Modbus;

namespace xpds_ProductMonitor.ViewModels
{
    public partial class MainWindowVM : ObservableObject
    {

        public MainWindowVM()
        {
            UpdateDateAndTime();
            getData();
        }

        private UserControl _monitorUC;


        public UserControl MonitorUC
        {
            get
            {
                if (_monitorUC == null)
                {
                    _monitorUC = new MonitorUserControl();
                }

                return _monitorUC;
            }
            set
            {
                _monitorUC = value;
                OnPropertyChanged(nameof(MonitorUC));
            }
        }

        #region 时间 日期

        //当前时间
        [ObservableProperty] public string timeStr = DateAndTime.Now.ToString("HH:mm");

        /// <summary>
        /// 程序运行后持续更新时间
        /// </summary>
        public void UpdateDateAndTime()
        {
            int date = DateAndTime.Weekday(DateTime.Now, FirstDayOfWeek.Sunday);
            string[] strArr = new[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };

            //初始化定时器 DispatcherTimer与Timer类似，但是它是在UI线程上运行的,所以可以直接操作UI,
            //而Timer不行,Timer是在另一个线程上运行的,不能直接操作UI,需要使用Dispatcher.Invoke
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(60); //每隔60秒更新一次
            //设置定时器的Tick事件
            timer.Tick += (s, e) =>
            {
                TimeStr = DateAndTime.Now.ToString("HH:mm");
                DateStr = DateAndTime.Now.ToString("yy-MM-dd");
                WeekStr = strArr[date - 1];
            };
            timer.Start();
        }

        //当前日期
        [ObservableProperty] public string dateStr = DateAndTime.Now.ToString("yy-MM-dd");

        //当期星期
        [ObservableProperty] public string weekStr = "星期一";

        #endregion

        #region 计数

        //机台总数
        [ObservableProperty] private string machineCount = "0134";


        //生产计数
        [ObservableProperty] private string productCount = "1111";


        //不良计数
        [ObservableProperty] private string badCount = "1111";


        #endregion

        #region 环境监控数据

        [ObservableProperty]
        private List<EnvironmentModel> environmentModelList = new List<EnvironmentModel>()
        {
            new EnvironmentModel() { EnvironmentName = "光照(Lux)", EnvironmentValue = 123 },
            new EnvironmentModel() { EnvironmentName = "噪音(db)", EnvironmentValue = 55 },
            new EnvironmentModel() { EnvironmentName = "温度(℃)", EnvironmentValue = 22 },
            new EnvironmentModel() { EnvironmentName = "湿度(%)", EnvironmentValue = 44 },
            new EnvironmentModel() { EnvironmentName = "PM2.5(m³)", EnvironmentValue = 11 },
            new EnvironmentModel() { EnvironmentName = "硫化氢(PPM)", EnvironmentValue = 55 },
            new EnvironmentModel() { EnvironmentName = "氮气(PPM)", EnvironmentValue = 66 }
        };

        #endregion


        #region 报警数据

        [ObservableProperty]
        public List<AlarmModel> alarmModelList = new List<AlarmModel>()
        {
            new AlarmModel { Num = "01", Msg = "设备温度过高", Time = "2023-11-23 18:34:56", Duration = 7 },
            new AlarmModel { Num = "02", Msg = "车间温度过高", Time = "2023-12-08 20:40:59", Duration = 10 },
            new AlarmModel { Num = "03", Msg = "设备转速过快", Time = "2024-01-05 12:24:34", Duration = 12 },
            new AlarmModel { Num = "04", Msg = "设备气压偏低", Time = "2024-02-04 19:58:00", Duration = 90 }
        };


        #endregion

        #region 设备监控

        [ObservableProperty]
        public List<DeviceModel> deviceModelList = new List<DeviceModel>()
        {
            new DeviceModel { DeviceItem = "电能(Kw.h)", Value = 60.8 },
            new DeviceModel { DeviceItem = "电压(V)", Value = 390 },
            new DeviceModel { DeviceItem = "电流(A)", Value = 5 },
            new DeviceModel { DeviceItem = "压差(kpa)", Value = 13 },
            new DeviceModel { DeviceItem = "温度(℃)", Value = 36 },
            new DeviceModel { DeviceItem = "振动(mm/s)", Value = 4.1 },
            new DeviceModel { DeviceItem = "转速(r/min)", Value = 2600 },
            new DeviceModel { DeviceItem = "气压(kpa)", Value = 0.5 }
        };


        #endregion

        #region 雷达监控能耗

        [ObservableProperty]
        public List<RaderModel> raderModelList = new List<RaderModel>()
        {
            new RaderModel { ItemName = "排烟风机", Value = 90 },
            new RaderModel { ItemName = "客梯", Value = 30.00 },
            new RaderModel { ItemName = "供水机", Value = 34.89 },
            new RaderModel { ItemName = "喷淋水泵", Value = 69.59 },
            new RaderModel { ItemName = "稳压设备", Value = 20 }
        };


        #endregion

        #region 缺岗员工属性

        /// <summary>
        /// 缺岗员工
        /// </summary>
        [ObservableProperty]
        private List<StuffOutWorkModel> stuffOutWorkList = new List<StuffOutWorkModel>()
        {
            new StuffOutWorkModel { StuffName = "张晓婷", Position = "技术员", OutWorkCount = 123 },
            new StuffOutWorkModel { StuffName = "李晓", Position = "操作员", OutWorkCount = 23 },
            new StuffOutWorkModel { StuffName = "王克俭", Position = "技术员", OutWorkCount = 134 },
            new StuffOutWorkModel { StuffName = "陈家栋", Position = "统计员", OutWorkCount = 143 },
            new StuffOutWorkModel { StuffName = "杨过", Position = "技术员", OutWorkCount = 12 }
        };


        #endregion

        #region 车间

        /// <summary>
        /// 车间
        /// </summary>
        [ObservableProperty]
        private List<WorkShopModel> workShopList = new List<WorkShopModel>()
        {
            new WorkShopModel
                { WorkShopName = "贴片车间", WorkingCount = 32, WaitCount = 8, WrongCount = 4, StopCount = 0 },
            new WorkShopModel
                { WorkShopName = "封装车间", WorkingCount = 20, WaitCount = 8, WrongCount = 4, StopCount = 0 },
            new WorkShopModel
                { WorkShopName = "焊接车间", WorkingCount = 68, WaitCount = 8, WrongCount = 4, StopCount = 0 },
            new WorkShopModel { WorkShopName = "贴片车间", WorkingCount = 68, WaitCount = 8, WrongCount = 4, StopCount = 0 }
        };


        #endregion

        #region 机台集合属性

        /// <summary>
        /// 机台集合属性
        /// </summary>
        [ObservableProperty] private List<MachineModel> machineList = new List<MachineModel>();



        private async Task InitiateMachineList()
        {
            await Task.Run(() =>
            {
                Random random = new Random();
                for (int i = 0; i < 20; i++)
                {
                    int plan = random.Next(100, 1000); //计划量 随机数
                    int finished = random.Next(0, plan); //已完成量
                    MachineList.Add(new MachineModel
                    {
                        MachineName = "焊接机-" + (i + 1),
                        FinishedCount = finished,
                        PlanCount = plan,
                        Status = "作业中",
                        OrderNo = "H202212345678"
                    });
                }
            });
        }

        #endregion

        #region 读取环境数据

        private async Task getData()
        {
            SerialInfo serialInfo = new SerialInfo();
            var rtu = RTU.getInstance(serialInfo);
            //环境信息
            while (true)
            {
                try
                {
                    ushort[] value = rtu.ReadHoldRegister(1, 0, 7); //从设备地址,寄存器开始地址,读取个数

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        for (int i = 0; i < 7; i++)
                        {
                            EnvironmentModelList[i].EnvironmentValue = value[i]; //更新环境数据
                        }
                        //员工缺勤信息
                        StuffService stuffService = new StuffService();
                        StuffOutWorkList = stuffService.getList().Data;
                    });

                    await Task.Delay(1000); //1秒钟更新一次数据
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    break;
                }
            }

        }
        #endregion
    }


}
